// pages/login/login.js
import { ComponentWithStore } from "mobx-miniprogram-bindings";
import { userStore } from "../../store/userStore";
import {
  loginService,
  getUserInfoService,
  registService,
  getPhoneService
} from "../../api/user";
import { setStorage } from "../../utils/storage";
ComponentWithStore({
  // 让页面和store对象建立联系
  storeBindings: {
    store: userStore,
    fields: ["token", "userInfo", "isLogin"],
    actions: ["setToken", "setUserInfo", "setIsLogin"],
  },

  /**
   * 页面的初始数据
   */
  data: {
    login: 1,
    userName: "",
    userPhone: "",
    userEmail: "",
    inSchool: "",
    schoolName: "就读学校",
    grade: "目前年级",
    schoolMajor: "专业名称",
    openid: "",
    access_token: "",
    nokuaizubook: false,
    registed: false, // 是否已经注册
    ShowMajor: false,
    ShowSchool: false,
    ShowGrade: false,
    majorId: -1,
    gradeId: -1,
  },

  methods: {
    // 登录首页
    login1() {
      this.setData({
        login: 2,
      });
    },

    // 获取昵称
    userName(e) {
      const userName = e.detail.value.trim();
      this.setData({
        userName: userName,
      });
    },
    kuaizubook() {
      wx.navigateTo({
        url: "../kuaizubook/kuaizubook",
      });
    },
    toggleKuaizubook() {
      this.setData({
        nokuaizubook: !this.data.nokuaizubook,
      });
    },
    //获取手机号码
    async login2() {
      console.log("用户昵称:", this.data.userName);
      if (!this.data.userName) {
        wx.showToast({
          title: "请输入昵称",
          icon: "none",
        });
        return;
      }
      if (!this.data.nokuaizubook) {
        wx.showToast({
          title: "同意快组用户协议以继续",
          icon: "none",
        });
        return;
      }
      this.setData({
        login: 3,
      });
    },

    // 前端获取微信手机号快捷注册
    async getPhoneNumber(e) {
      if (e.detail.errMsg !== "getPhoneNumber:ok") {
        wx.showToast({
          title: "用户拒绝授权",
          icon: "none",
        });
        return;
      }
      const code = e.detail.code;
      try {
        const res = await getPhoneService(code);
        console.log(res);
        const phoneNumber = res.data.phoneNumber;
        console.log(phoneNumber);
        this.setData({
          userPhone: phoneNumber,
        });
      } catch (error) {
        console.error("获取用户手机号失败", error);
        wx.showToast({
          title: "获取手机号失败，请重试",
          icon: "none",
        });
        return;
      }
      this.setData({
        login: 4,
      });
    },

    // 获取邮件
    userEmail(e) {
      const userEmail = e.detail.value;
      this.setData({
        userEmail: userEmail,
      });
    },
    login4() {
      const reg = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
      if (!reg.test(this.data.userEmail)) {
        wx.showToast({
          title: "请输入有效邮箱",
          icon: "none",
        });
        return;
      }
      this.setData({
        login: 5,
      });
    },

    // 获取学校信息
    onSchoolPickerClose(e) {
      this.setData({ ShowSchool: e.detail.show });
    },
    onSchoolChange(e) {
      const selectedSchool = e.detail.item; // 获取传递的学校对象
      console.log(
        "选中学校:",
        selectedSchool.schoolname,
        "ID:",
        selectedSchool.id,
      );
      this.setData({
        inSchool: selectedSchool.id, // 存储学校ID
        schoolName: selectedSchool.schoolname, // 更新显示的学校名称
      });
    },
    // 打开选择学校页面
    showSchoolPicker() {
      this.setData(
        {
          ShowSchool: true,
        },
        () => {
          console.log("ShowSchool 状态:", this.data.ShowSchool);
        },
      );
    },

    // 获取年级信息
    onGradePickerClose(e) {
      this.setData({ ShowGrade: e.detail.show });
    },
    onGradeChange(e) {
      const selectedGrade = e.detail.item;
      this.setData({
        grade: selectedGrade.value,
        gradeId: selectedGrade.id, // 存储年级ID
      });
    },
    // 打开选择年级页面
    showGradePicker() {
      this.setData(
        {
          ShowGrade: true,
        },
        () => {
          console.log("ShowGrade 状态:", this.data.ShowGrade);
        },
      );
    },

    schoolMajor(e) {
      const schoolMajor = e.detail.value;
      this.setData({
        schoolMajor: schoolMajor,
      });
    },
    showMajorPicker() {
      this.setData(
        {
          ShowMajor: true,
        },
        () => {
          console.log("ShowMajor 状态:", this.data.ShowMajor);
        },
      );
    },
    onMajorPickerClose(e) {
      this.setData({ ShowMajor: e.detail.show });
    },
    onMajorChange(e) {
      const selectedMajor = e.detail.item; // 获取传递的专业对象
      console.log(
        "选中专业:",
        selectedMajor.majorName,
        "ID:",
        selectedMajor.majorClassId,
      );
      this.setData({
        schoolMajor: selectedMajor.majorName, // 更新显示的专业名称
        majorId: selectedMajor.id, // 存储专业ID
      });
    },

    //最终登录
    async fastLogin() {
      try {
        const code = (await wx.login()).code;
        const res = await loginService(code);
        console.log(res);

        setStorage("token", res.data);
        this.setToken(res.data);

        await this.getUserInfo();
        this.setIsLogin(true);

        wx.navigateTo({
          url: "../welcome/loginGreeting",
        });
      } catch (error) {
        console.error("登录失败:", error);
        if (error.data?.code === 99999) {
          wx.showModal({
            title: "提示",
            content: "您还未注册，请先注册",
            confirmText: "去注册",
            cancelText: "取消",
            success: (res) => {
              if (res.confirm) {
                this.login1(); // 调用注册流程
              }
            }
          });
        } else {
          wx.showToast({
            title: error.data?.message || "登录失败，请重试",
            icon: "none",
          });
        }
      }
    },

    test() {
      this.setData({
        login: 5,
      });
    },

    async getUserInfo() {
      try {
        const { data } = await getUserInfoService();
        console.log("取得用户信息", data);
        
        // 用户信息包含openid
        const userInfoWithOpenid = {
          ...data,
        };
        
        // 将用户信息存储到本地
        setStorage("userInfo", userInfoWithOpenid);

        // 将用户信息存储到store对象
        this.setUserInfo(userInfoWithOpenid);
      } catch (error) {
        console.error("获取用户信息失败:", error);
        throw error;
      }
    },

    async signup() {
      const { userName, userPhone, userEmail, inSchool, gradeId, majorId } =
        this.data;

        if (!inSchool || inSchool === '') {
          wx.showToast({
            title: '请选择就读学校',
            icon: 'none'
          });
          return;
        }

        if (gradeId === -1) {
          wx.showToast({
            title: '请选择年级',
            icon: 'none'
          });
          return;
        }
        
        if (majorId === -1) {
          wx.showToast({
            title: '请选择专业',
            icon: 'none'
          });
          return;
        }
      try {
        // 1. 注册逻辑
        const res = await registService({
          jsCode: (await wx.login()).code,
          phone: userPhone,
          nickname: userName,
          email: userEmail,
          school: inSchool,
          grade: gradeId,
          major: majorId,
        });
        console.log(res);
        setStorage("token", res.data);
        this.setToken(res.data);
        await this.getUserInfo();

        wx.navigateTo({
          url: "../welcome/registerGreeting",
        });
      } catch (err) {
        console.error("操作失败:", err);
        //wx.showToast({ title: err.data.message, icon: "none" });
        // 处理"已经注册过"的情况
        if(err.data && err.data.message && err.data.message.includes('你已经注册过了')){
          // 显示提示信息并阻止跳转
          wx.showModal({
            title: '提示',
            content: '您已经注册过了，请直接登录',
            showCancel: true,
            cancelText: '返回',
            confirmText: '去登录',
            success: (res) => {
              if(res.confirm){
                this.setData({
                  login: 1
                })
              }
            }
          });
        }else{
          // 其他错误情况
          wx.showToast({ 
            title: err.data.message || '注册失败，请重试', 
            icon: "none",
            duration: 2000 // 延长显示时间
          });
        }
      }
    },
  },
});